<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;
use pmhapp\Curl;

//定义常量


const SSL = 'https://';

class Api extends Bases 
{
    
    public function ceshi(){
      return SSL;
    }   
    
    public function ceshi3(){
        //dump(Curl::the_key());
       //dump(Curl::get('https://gitee.com'));
       

       return $this->pmhapp->异步发消息('TgAiBot001','测试','https://t.me/fw688');
    }
    
    public function zidong(){
    
        $MadelineProto = new \danog\MadelineProto\API('session.pmhapp');//session 加载序列化会话 创建序列会话
        $MadelineProto->start();
        
        
        $me = $MadelineProto->getSelf();
        
        $MadelineProto->logger($me);
        
        if (!$me['bot']) {
            // $MadelineProto->messages->sendMessage(['peer' => 'https://t.me/PMHW_bot', 'message' => '获取失败']);
        }
        $MadelineProto->echo('OK, done!');
        $MadelineProto->messages->sendMessage(['peer' => 'https://t.me/PMHW_bot', 'message' => '自动推送消息测试']);
        $MadelineProto->messages->sendMessage(['peer' => 'https://t.me/ququn_bot', 'message' => '自动推送消息测试']);
        return "登录成功";
    }
    
    /**
     * 判断登录
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * 
    **/
    
    public function is_login(){
        

       if(!$me['bot']){
           exit(json_encode(['code'=>1,'msg'=>'未登录']));
       }
       exit(json_encode(['code'=>0,'msg'=>'已登录']));
    }
    
    /**
     * 添加实例 
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * 
     * $name @ 序列化名称
    **/
    
    public function iframe_addAiBot(){
       //error_reporting(E_ALL^E_NOTICE^E_WARNING);
       error_reporting(E_ALL^E_NOTICE^E_WARNING);
       $name = input('get.name');
       $res = Db::name('example')->where(['name'=>$name])->find();
       
        if($res){
          exit("该名称已被占用，请更换");
       }
       
       $count = Db::name('example')->where(['userId'=>$this->userId])->count();
       if($count == $this->_user['example_count'] && $this->_user['example_count']){
           exit("您已创建" . $this->_user['example_count'] . "个实例<br/>已达最大限制！<br/> 请联系管理扩容"); 
       }
       
       $session = $this->pmhapp->session($name);
       
       $me = $session->getSelf();
       
       if (!$me['first_name']) {
         return "添加失败";
         exit();
       }
       
       $data['name'] = $name;
       $data['username'] = $me['first_name'];
       $data['time'] = time();
       $data['userId'] = $this->userId;
       $insert = Db::name('example')->insert($data);
       
       return "添加成功";
    }
    
    /**
     * 退出实例登录
     * $name @  实例名
     * $username @ 用户名
    **/
    public function outlogin(){
        $name = input('get.name');
        $username = input('get.username'); 
        if(!$name || !$username)
        
        $delete = Db::name('example')->where(['username'=>$username,'userId'=>$this->userId])->delete();
        if(!$delete){
            json_exit(1,'删除失败');
        }
        
        $dir = $_SERVER['DOCUMENT_ROOT'];
        
        $file = get_file($dir);
        
        foreach ($file as $value){
            if(strpos($value,$name) !== false){
                unlink($value);
            }
        }
        

        
        json_exit(0,'退出成功');
    }
    
    
    /**
     * 共享群接口
     * 
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * $qun @ 群昵称或者群链接
     * $url @ 加群链接
     * $type @ 群类型
     * $is_verify @ 是否需要加群验证
    **/
    public function add_share_qun(){
        $qun = trim(input('post.qun'));
        if(!$qun || $qun == ''){json_exit(1,'缺少群链接或群NAME');}
        
        if(!strpos($qun,'https://t.me')){
            //包含
           $url = $qun;
           $qun = str_replace("https://t.me/","",$qun);
        }else{
           $url = 'tg://resolve?domain='.$qun;
        }
        
        
        //判断是否存在
        $judge = Db::name('TgQun')->where(['url'=>$url])->find();
        if($judge){
            json_exit(1,'该群已存在');
        }
        
        
        $type = input('post.type');
        if(!$type || $type == ''){json_exit(1,'缺少群类型');}
        
        $is_verify = input('post.is_verify');
        
        $data['name'] = $qun;
        $data['url'] = $url;
        $data['is_verify'] = $is_verify;
        $data['time'] = time();
        $data['gt_id'] = $type;
        
        $insert = Db::name('TgQun')->insert($data);
        if(!$insert){json_exit(1,'共享失败');}
        
        json_exit(0,'共享成功');
    }
    
    /**
     * 创建加群配置
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * 
     * $example @ 实例ID
     * $data @ 加群列表
     * $userId @ 用户ID
    **/
    
    public function get_config(){
        $example = input('post.example');
        $data = input('post.data');
        $_data = HandleArrays($data);
        
        $data = json_decode($_data, true);
        if(!$example){json_exit(1,'实例名不存在');}
        if(!$data[0]){json_exit(1,'群不存在');}
        
        $datas['exampleId'] = $example;
        $datas['data'] = HandleType($data);
        $datas['userId'] = $this->userId;
        $datas['time'] = time();
        
        $insert = Db::name('JoinQunConfig')->insert($datas);
        if(!$insert){json_exit(1,'创建失败');}
        json_exit(0,'创建成功');
    }
    
    /**
     * 创建群发广告配置
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * 
     * $data['exampleId'] @ 实例ID
     * $data['timing'] @ 每小时群发次数
     * $data['typeId']  @ 类型 文字=1 图片=2
     * $data['content'] @群发内容
     * $data['image'] @图片地址
     * $data['data'] @JSON格式群发ID
    **/  
    public function add_qunfa(){
        $data['exampleId'] = input('post.example');
        $data['timing'] = input('post.timing');
        $data['typeId'] = input('post.typeId');
        $data['content'] = input('post.content');
        $data['image'] = input('post.image');
        $data['image'] = HandleArrays($data['image']);
        
        $data['data'] = input('post.data');
        $data['data'] = HandleArrays($data['data']);
        $data['time'] = time();
        $data['userId'] = $this->userId;
        $_data = json_decode($data['data'],true);
        $data['data'] = HandleType($_data);
        if(!$data['exampleId']){json_exit(1,'实例为空');}
        if(!$data['timing']){json_exit(1,'群发次数为空/小时');}
        if(!$data['typeId']){json_exit(1,'类型为空');}
        // if(!$data['content']){if($data['typeId']==1){json_exit(1,'内容为空');}else{json_exit(1,'图片为空');}}
        if(!$data['content']){json_exit(1,'发送数据不能为空');}
        if(!$_data[0]){json_exit(1,'群不存在');}
        
        //Timing of mass
        $insert = Db::name('TimingOfMass')->insert($data);
        if(!$insert){
            json_exit(1,'创建失败');
        }
        json_exit(0,'创建成功');
        
    }
    
    //接收图片上传
    public function img_upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            $imgType = $info->getExtension();
            $imgUrl = 'uploads/' . $info->getSaveName();
            if($imgType !== 'png' && $imgType !== 'jpg' && $imgType !== 'jpeg'){
                //文件格式不正确 删除文件
                unlink(ROOT_PATH . 'public/' . $imgUrl);
                json_exit(1,'文件格式不正确！');
            }
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                // echo $info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                json_exit(0,'上传成功',$imgUrl);
 
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }
    }
    
    /** 
     * 启动群发任务
     * 
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * 
     * $id 任务主键ID
     * $ScriptName 脚本命名
     * $url 请求地址
     * $TheKey 密钥
     * $perform_url 循环执行脚本地址
    **/
    
    public function start_tom($id){
        
        $url_ssl = 'https://';
    
        $tom = Db::name('TimingOfMass')->where(['id'=>$id])->find();
        if($tom['userId'] != $this->userId){json_exit(1,'权限不足');}
        if($tom['type'] == 1){json_exit(1,'该任务已启动');}
        
        if(!$tom['script_name']){
            $ScriptName = $this->userId . "_" . time() . '_' . $id;
        }else{
            $ScriptName = $tom['script_name'];
        }
        
        if(!$tom['key']){
            $TheKey = Curl::the_key(16);
        }else{
            $TheKey = $tom['key'];
        }
        
        //老方法 生成定时脚本 进行请求
        // if(!$tom['script_name']){
        //     $url = $this->file_tom($ScriptName,$id,$TheKey);
        // }else{
        //     $server_name = $_SERVER["SERVER_NAME"];
        //     $config = fopen("script/".$ScriptName, "w") or die("Unable to open file!");
        //     $txt = 1;
        //     fwrite($config,$txt);
        //     $url = $url_ssl.$server_name."/index/Script/script_timing/name/".$ScriptName."/id/".$id."/key/".$TheKey; //请求接口
        // }
        
        
        //$perform_url = $url_ssl.$_SERVER["SERVER_NAME"]."/script/".$ScriptName.".php";
        
        //修复 2022/1/4 1:15
        //Curl::get($url);
        //Curl::curl_get($perform_url);
        
                
        // $tom = Db::name('TimingOfMass')->where(['id'=>$id])->update(['type'=>1,'key'=>$TheKey,'script_name'=>$ScriptName]);
        // if(!$tom){
        //   json_exit(1,'启动失败');
        // }
        
        //最新宝塔面板脚本方法
        $server_name = $_SERVER["SERVER_NAME"];

        $url = SSL.$server_name."/index/Script/script_timing/name/".$ScriptName."/id/".$id."/key/".$TheKey; //请求接口
        $res = TimingTask($ScriptName,$url);
        
                
        $tom = Db::name('TimingOfMass')->where(['id'=>$id])->update(['type'=>1,'key'=>$TheKey,'script_name'=>$ScriptName,'bt_id'=>$res['id']]);
        if(!$tom){
           json_exit(1,'启动失败');
        }
        

        
        json_exit(0,'启动成功');
    }
 
    /** 
     * 关闭群发任务
     * 
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * 
    **/   
    public function off_tom($id){
       $tom = Db::name('TimingOfMass')->where(['id'=>$id])->find();
       if($tom['userId'] != $this->userId){json_exit(1,'权限不足');} 
       if($tom['type'] == 0){json_exit(1,'该任务已关闭');}
       $update = Db::name('TimingOfMass')->where(['id'=>$id])->update(['type'=>0]);

       $res = Db::name('TimingOfMass')->where(['id'=>$id])->find();
        // $config = fopen("script/".$tom['script_name'], "w") or die("Unable to open file!");
        // $txt = 2;
        // fwrite($config,$txt);
        
        DeleteTimingTask($res['bt_id']);
        
        json_exit(0,'关闭成功');
    }
    
    
    /** 
     * 定时任务生成
     * 
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * 
     * $name @ 脚本名
     * $id @ 参数 数据库
     * $TheKey @ 密钥防止恶意调用 存入数据库
    **/ 
    public function file_tom($name,$id,$TheKey){

        if(!$name){json_exit(1,'缺少脚本名');}
        $server_name = $_SERVER["SERVER_NAME"];
        //生成开关文件
        $config = fopen("script/".$name, "w") or die("Unable to open file!");
        $txt = 1;
        fwrite($config,$txt);
        
        //生成脚本
        $script = fopen("script/".$name.".php", "w") or die("Unable to open file!");
        $time = 15;//间隔时间 s
        $url = "http://".$server_name."/script/".$name.".php";//循环执行访问
        $_url = "http://".$server_name."/index/Script/script_timing/name/" . $name . "/id/".$id."/key/".$TheKey; //请求接口
        
        $txt = '<?php'."\n";
        fwrite($script, $txt);

        $txt = 'do{'."\n";
        fwrite($script, $txt);
        
        $txt = '$a = file_get_contents("'.$name.'");'."\n";
        fwrite($script, $txt);
        
        $txt = 'if($a != 1){die("process abort");}'."\n";
        fwrite($script, $txt);       
        
        $txt = 'sleep('.$time.');'."\n";
        fwrite($script, $txt);  
        
        $txt = 'geturl("'.$_url.'");'."\n";
        fwrite($script, $txt);
        
        $txt = 'geturl("'.$url.'");'."\n";
        fwrite($script, $txt);

        $txt = '}while($a==1);'."\n\n";
        fwrite($script, $txt);  
 
        $txt = 'function geturl($url){
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
        }'."\n";   
        fwrite($script, $txt);
        
        
        $txt = '?>';
        fwrite($script, $txt);
        
        fclose($script);
        
        return $_url;
    }
    
    
    
    /**
     * 获取当前实例创建的群列表
    **/
    
    public function qun_list(){
        $name = input('get.name');
        if($name=''){json_exit(1,'name参数不存在');}
        
        $list = $this->pmhapp->异步聊天($name);
        $_list = [];
        foreach($list as $val){
            
            //channel 
            if($val['_'] == 'chat'){
                    array_push($_list,$val);
            }
        }
        
        return json($_list);
    }
    
    // +----------------------------------------------------------------------
    // | 分割线程序执行相关接口
    // +----------------------------------------------------------------------
    // | 作者:  <qq32579135>
    // +----------------------------------------------------------------------
    
    /**
     * 自动加群
     * 
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * $id @ 配置ID
     * 
     * $join_qun_config @配置数据
     * $example @实例数据
    **/
    
    public function jiaqun(){
        $id = input('get.id');
        if(!$id){json_exit(1,'缺少ID');}
        //查询配置
        $join_qun_config = Db::name('JoinQunConfig')
        ->where(['id'=>$id])->find();
        if($join_qun_config['userId'] != $this->userId){json_exit(1,'权限不足');}
        if($join_qun_config['type'] == 1){json_exit(1,'已执行过');}
        //查询实例
        $example = Db::name('example')->where(['id'=>$join_qun_config['exampleId']])->find();
        if(!$example){json_exit(1,'实例不存！在请检测。');}

        
        //实例化

        // 弃用方案1
        // $keys = json_decode($join_qun_config['data'],true);
        
        // //提取群url
        // foreach ($keys as $key => &$value){
        //     $TgQun = Db::name('TgQun')->where(['id'=>$value['qunId']])->find();
        //     $value['url'] = $TgQun['url'];
        // }
        
        // $count = count($keys) - 1;
        
        // foreach($keys as $k => &$v){
            
        //     $InputChannel = $v['url'];
            
        //     $data = $this->pmhapp->加群($example['name'],$InputChannel);

        //     if($data['chats'][0]["username"]){
        //         $v['type'] = 1;
        //     }
        //     if($count == $k){
        //         break;
        //     }
        // }        
        
        //方案2
        $keys = json_decode($join_qun_config['data'],true);
        
        //提取群url
       
        foreach ($keys as $key => &$value){
            $TgQun = Db::name('TgQun')->where(['id'=>$value['qunId']])->find();
            $value['url'] = $TgQun['url'];
        }
        
        $url = [];
        foreach($keys as $k => &$v){
            $InputChannel = $v['url'];
            array_push($url,$InputChannel);
            $v['type'] = 1;
        }   
        
        //dump($url);
        //echo 1;
        
        $ybjq = $this->pmhapp->异步加群($example['name'],$url);
        //dump($ybjq);
        
        $data = json_encode($keys);
        //dump($data);

        Db::name('JoinQunConfig')->where(['id'=>$id])->update(['data'=>$data]);
        //修改配置状态
        Db::name('JoinQunConfig')->where(['id'=>$id])->update(['type'=>1]);
    
        json_exit(0,'执行完成');
    } 
    
    /**
     * 自动群发消息 测试
     * 
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * $id @ 配置ID
     * 
     * $tom @任务数据
     * $example @实例数据
    **/    
        
    public function ceshi_tom(){
        $id = input('get.id');
        if(!$id){json_exit(1,'缺少id');}
        $server_name = $_SERVER["SERVER_NAME"];
        $tom = Db::name('TimingOfMass')->where(['id'=>$id])->find();
        if($tom['userId'] != $this->userId){json_exit(1,'权限不足');}
        //查询实例
        $example = Db::name('example')->where(['id'=>$tom['exampleId']])->find();
        if(!$example){
            exit();
        }
        
        $data = json_decode($tom['data'],true);
        $url = [];
        //提取群url
        foreach ($data as $key => &$value){
            $TgQun = Db::name('TgQun')->where(['id'=>$value['qunId']])->find();
            array_push($url,$TgQun['url']);
        }       
        
        $tom['image'] = json_decode($tom['image'],true);
        
        
        
        if($tom['content'] && empty($tom['image'])){
            //true true
            $this->pmhapp->异步发消息($example['name'],$tom['content'],$url);
        }else if(!$tom['content'] && !empty($tom['image'])){
            //true true
            foreach ($tom['image'] as $key){
               $imgurl = SSL.$server_name.'/'.$key;
               $this->pmhapp->异步发媒体($example['name'],$imgurl,$tom['content'],$url);  
            }
        }else{
            foreach ($tom['image'] as $key){
               $imgurl = SSL.$server_name.'/'.$key;
               $this->pmhapp->异步发媒体($example['name'],$imgurl,$tom['content'],$url);  
            }
        }
        
    }
    
    /**
     * 删除自动加群配置
     * 
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * $id @ 配置ID
     * 
    **/
    
    public function delete_config($id){
        if(!$id){json_exit(1,'缺少ID');}
        
        $delete = Db::name('JoinQunConfig')->where(['id'=>$id,'userId'=>$this->userId])->delete();
        if(!$delete){json_exit(1,'删除失败');}
        json_exit(0,'删除成功');
    }
    
    /**
     *删除群发任务
     * 
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * $id @ 任务ID
    **/
    
    public function delete_tom($id){
        if(!$id){json_exit(1,'缺少ID');}
        $tom = Db::name('TimingOfMass')->where(['id'=>$id])->find();
        
        $delete = Db::name('TimingOfMass')->where(['id'=>$id,'userId'=>$this->userId])->delete();
        if(!$delete){json_exit(1,'删除失败');}
        json_exit(0,'删除成功');
    }
}


 